#include "MicRecorder.h"

//MicRecorder
MicRecorder::MicRecorder(QObject *parent)
    :QObject(parent)
{
    m_audioInput = nullptr;       
    m_timeId = -1;
}

MicRecorder::~MicRecorder()
{
    stopRecord();
}

void MicRecorder::timerEvent(QTimerEvent *e)
{
    m_data.push_back(m_audioBuffer->readAll());
}

bool MicRecorder::isRecord()
{
    return m_audioInput;
}

QByteArray MicRecorder::micData()
{
    return m_data;
}

void MicRecorder::startRecord(QAudioFormat format)
{    
    Q_ASSERT(!m_audioInput);

    m_data.clear();
    m_audioInput = new QAudioInput(format);
    m_audioBuffer = m_audioInput->start();   
    m_timeId = startTimer(50);
}

void MicRecorder::stopRecord()
{    
    if (m_audioInput)
    {
        m_data.push_back(m_audioBuffer->readAll());

        m_audioInput->stop();
        m_audioInput->deleteLater();
        m_audioInput = nullptr;
        killTimer(m_timeId);
    }
}